<?php

namespace App\Http\Controllers\Pc;

use App\Http\Controllers\Controller;
use App\Models\AmazonPlaceOrderContractModel;
use App\Models\BaseModel;
use App\Models\Common\Constant;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AmazonPlaceOrderContractController extends Controller
{
    protected $request;
    protected $model;

    public function __construct(Request $request)
    {
        $this->model = new AmazonPlaceOrderContractModel();
        $this->request = $request;
    }

    /**
     * @Desc: 保存下单合同
     * @return null
     * @author: Liu Sinian
     * @Time: 2023/4/16 10:59
     */
    public function saveAmazonPlaceOrderContract()
    {
        $params = $this->request->all();

//        if ($params['token'] != '69282C1B5216E0F401A7640DDB46C936'){
//            $this->back('合同保存功能维护中，预计2023-10-12 11:00:00维护完毕！');
//        }
        if (!isset($params['contract_class'])) {
            $this->back('请选择合同类别');
        }

        if (!isset($params['contract_items']) || empty($params['contract_items'])) {
            $this->back('未选择商品信息');
        }

        $class = $params['contract_class'];

        try {
            DB::begintransaction();
            //采购合同
            if ($class == 3) {
                $multiParams  = [];//多合同下单数组参数
                $items        = []; //根据供应商分数组
                $singleParams = $params;//单合同下单数组参数

                foreach ($params['contract_items'] as $v) {
                    if (!isset($v['suppliers_id']) || empty($v['suppliers_id'])) {
                        $this->back('保存失败！计划未绑定供应商');
                    }
                    $items[$v['suppliers_id']][] = $v;
                }

                foreach ($items as $item) {
                    $singleParams['contract_items'] = $item;
                    $bindPlaceIds                   = '';

                    $contractTotalAmount = $totalNum = $supplierId = $supplierNo = 0;
                    foreach ($item as $v) {
                        $placeId             = explode('-', $v['id'])[0];
                        $bindPlaceIds        .= $placeId . ',';
                        $supplierId          = $v['suppliers_id'];
//                        $supplierNo          = $v['suppliers_no'];
                        $contractTotalAmount += ($v['order_num'] * $v['price']);
                        $totalNum            += $v['order_num'];
                    }

                    $singleParams['bind_place_ids']        = rtrim($bindPlaceIds, ',');
                    $singleParams['contract_total_amount'] = $contractTotalAmount;
                    $singleParams['total_num']             = $totalNum;
                    $singleParams['supplier_id']           = $supplierId;
                    $singleParams['supplier_no']           = $supplierNo;
                    $multiParams[]                         = $singleParams;
                }
                $contractNo = '';
                foreach ($multiParams as $v) {
                    $contractNo .= $this->model->saveAmazonPlaceOrderContract($v) . ',';
                }
            } else {
                $contractNo = $this->model->saveAmazonPlaceOrderContract($params);
            }
            $contractNo = rtrim($contractNo, ',');
            $this->AddSysLog($params, $contractNo, '生产下单合同保存', __METHOD__);
            DB::commit();
            $this->back('保存成功！合同号：' . $contractNo, 200);
        } catch (\Exception $e) {
            DB::rollback();
            $this->back('保存失败！原因：' . $e->getMessage() . '，' . $e->getLine());
        }
    }

    /**
     * @Desc: 获取下单合同列表
     * @return null
     * @author: Liu Sinian
     * @Time: 2023/4/17 15:07
     */
    public function getAmazonPlaceOrderContractList()
    {
        $params = $this->request->all();
        $result = $this->model->getAmazonPlaceOrderContractList($params);

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }

    /**
     * @Desc: 删除下单合同
     * @return null
     * @author: Liu Sinian
     * @Time: 2023/4/17 15:06
     */
    public function deleteAmazonPlaceOrderContract()
    {
        $params = $this->request->all();
        $result = $this->model->deleteAmazonPlaceOrderContract($params);
        $this->AddSysLog($params, $result, '生产下单合同删除', __METHOD__);

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }

    /**
     * @Desc: 下单合同详情
     * @return null
     * @author: Liu Sinian
     * @Time: 2023/4/17 15:06
     */
    public function getAmazonPlaceOrderContractDetail()
    {
        $params = $this->request->all();
        $result = $this->model->getAmazonPlaceOrderContractDetail($params);
        // return $this->back('',200,$result);
        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }

    /**
     * @Desc: 计划详情选择器
     * @return null
     * @author: Liu Sinian
     * @Time: 2023/4/17 15:06
     */
    public function getAmazonPlaceOrderTaskDetail()
    {
        $params = $this->request->all();
        $result = $this->model->getAmazonPlaceOrderTaskDetail($params);

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }

    /**
     * @Desc: 采购下单计划详情选择器
     */
    public function getPurchaseAmazonPlaceOrderTaskDetail()
    {
        $params = $this->request->all();
        $result = $this->model->getPurchaseAmazonPlaceOrderTaskDetail($params);

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }

    /**
     * @Desc: 处理合同明细数据
     * @return null
     * @author: Liu Sinian
     * @Time: 2023/4/17 17:30
     */
    public function formatContractItems()
    {
        $params = $this->request->all();
        $result = $this->model->formatContractItems($params);

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }

    /**
     * @Desc:下单合同提交审核
     * @return null
     * @author: Liu Sinian
     * @Time: 2023/5/12 17:11
     */
    public function submitAmazonPlaceOrderContract()
    {
        $params = $this->request->all();
        $result = $this->model->submitAmazonPlaceOrderContract($params);

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }

    /**
     * @Desc:合同审核撤销
     * @return null
     * @author: Liu Sinian
     * @Time: 2023/5/16 9:11
     */
    public function revokeAmazonPlaceOrderContract()
    {
        $params = $this->request->all();
        $result = $this->model->revokeAmazonPlaceOrderContract($params);
        $this->AddSysLog($params, $result, '生产下单合同撤销', __METHOD__);

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }

    /**
     * @Desc:合同详情打印
     * @return null
     * @author: Liu Sinian
     * @Time: 2023/6/25 9:14
     */
    public function exportPlaceOrderContractDetail()
    {
        $params = $this->request->all();
        $result = $this->model->exportPlaceOrderContractDetail($params);

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }

    /**
     * @Desc:获取历史采购价
     * @return null
     * @author: Liu Sinian
     * @Time: 2023/7/14 10:26
     */
    public function getHistorySpuPrice()
    {
        $params = $this->request->all();
        $result = $this->model->getHistorySpuPrice($params);

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }

    /**
     * @Desc:补录合同（虚拟合同）
     * @return null
     * @author: Liu Sinian
     * @Time: 2023/7/26 14:18
     */
    public function additionalRecordingContract()
    {
        $params = $this->request->all();
        $result = $this->model->additionalRecordingContract($params);

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }

    /**
     * 绑定采购单号
     */
    public function bindPurchaseOrderNo()
    {
        $params = $this->request->all();

        if (!isset($params['contract_no']) && empty($params['contract_no'])) {
            $this->back('请选择合同');
        }else{
            if (!is_array($params['contract_no'])){
                $this->back('合同格式不正确！');
            }
        }

        if (!isset($params['purchase_order_no']) && empty($params['purchase_order_no'])) {
            $this->back('未给定采购单号');
        }

        $error = '';
        foreach ($params['contract_no'] as $contractNo){
            $data = [
                [
                    'contract_no'       => $contractNo,
                    'purchase_order_no' => $params['purchase_order_no']
                ]
            ];

            $result = $this->model->bindPurchaseOrderNo($data);

            if (isset($result['code']) && $result['code'] == 500){
                $error .= $result['msg'];
            }
        }
        if (!empty($error)){
            return $this->back('绑定出错!'.$error);
        }

        return $this->back('绑定成功', 200);
    }

    /**
     * 批量绑定采购单号
     */
    public function batchBindPurchaseOrderNo()
    {
        $params = $this->request->all();
        if (empty($params['file'])) {
            $this->back('未选择文件');
        }

        $params['row'] = ['contract_no', 'purchase_order_no'];
        $list          = (new BaseModel())->CommonExcelImport($params);

        if (!$list) {
            $this->back('请填写合同号和采购单号');
        }

        $result = $this->model->bindPurchaseOrderNo($list);

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }

    /**
     * @Desc:合同一键完结
     * @return array|null
     * @author: Liu Sinian
     * @Time: 2023/8/21 17:16
     */
    public function oneClickCompletionContract()
    {
        $params = $this->request->all();

        if (!isset($params['id']) || empty($params['id'])){
            return $this->back('未给定合同标识');
        }
        if (!is_array($params['id'])){
            return $this->back('合同标识格式不正确！');
        }
        try {
            db::beginTransaction();
            $result = $this->model->oneClickCompletionContract($params);

            db::commit();
        }catch (\Exception $e){
            db::rollback();

            return ['code' => 500, 'msg' => '一键完结操作失败！'.$e->getMessage().';'.$e->getLine()];
        }

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }

    public function getCompanyList()
    {
        $params = $this->request->all();
        $result = $this->model->getCompanyList($params);

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }

    public function getFormatContractItems()
    {
        $params = $this->request->all();
        $result = $this->model->getFormatContractItems($params);

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }

    public function getContractPaymentMethod()
    {
        $params = $this->request->all();
        $result = $this->model->getContractPaymentMethod($params);

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);

        $payment_settlement_method = [];
        foreach (Constant::CONTRACT_PERIODIC_SETTLEMENT_METHOD as $k => $v){
            $payment_settlement_method[] = [
                'id' => $k,
                'payment_settlement_method' => $v,
                'payment_information' => Constant::CONTRACT_PAYMENY_INFORMATION[$k]
            ];
        }

        return ['code' => 200, 'msg' => '获取成功！', 'data' => $payment_settlement_method];
    }

    public function getContractPdfPath(){
        $params = $this->request->all();
        $result = $this->model->getContractPdfPath($params);

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }

    public function batchUpdateContractPdf()
    {
        $params = $this->request->all();
        $result = $this->model->batchUpdateContractPdf($params);

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }

    public function uploadContractFile()
    {
        $params = $this->request->all();
        $result = $this->model->uploadContractFile($params);

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }

    /**
     * @Desc:获取采购单跟进报表
     * @return null
     * @author: Liu Sinian
     * @Time: 2023/10/12 11:44
     */
    public function getOrderReportForms()
    {
        $params = $this->request->all();
        $result = $this->model->getOrderReportForms($params);

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }

    public function getContractReportForms()
    {
        $params = $this->request->all();
        $result = $this->model->getContractReportForms($params);

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }

    public function getContractPlanList()
    {
        $params = $this->request->all();
        $result = $this->model->getContractPlanList($params);

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }

    public function getContractSpuList()
    {
        $params = $this->request->all();
        $result = $this->model->getContractSpuList($params);

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }

    public function downloadContractExcel()
    {
        $params = $this->request->all();
        $result = $this->model->downloadContractExcel($params);

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }

    public function saveContractPaymentMethod()
    {
        $params = $this->request->all();
        $result = $this->model->saveContractPaymentMethod($params);

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }
}